#include "ConnectionManager.h"

ConnectionManager::ConnectionManager() : currentMaxID_(1), eraseClosedConnectionTimer_(3000)
{

}

void ConnectionManager::start(ConnectionPtr c)
{
	LogFunctionEnter;

	c->setID( currentMaxID_++ );

	connections_.insert(std::make_pair(c->getID(),c));

	c->start();
}

void ConnectionManager::stop(ConnectionPtr c)
{
	LogFunctionEnter;
	//connections_.erase(c->getID());
	c->stop(false);
}

void ConnectionManager::stop_all()
{
	LogFunctionEnter;

	ConnectionMapType::iterator it = connections_.begin();
	for (; it != connections_.end(); ++it)
	{
		it->second->stop(false);
	}

//  	std::for_each(connections_.begin(), connections_.end(),
//  		boost::bind(&Connection::stop, _1));
	connections_.clear();
}

void ConnectionManager::update(uint32 timeElapse)
{
	eraseClosedConnectionTimer_.update(timeElapse);
	if (eraseClosedConnectionTimer_.passed())
	{
		eraseClosedConnectionTimer_.reset();
		ConnectionMapType::iterator it = connections_.begin();
		for (; it != connections_.end();)
		{
			if (it->second->isStopped())
			{
				it = connections_.erase(it);
			}
			else
			{
				++it;
			}
		}
	}

	ConnectionMapType::iterator it = connections_.begin();
	for (; it != connections_.end(); ++it)
	{
		it->second->update(timeElapse);
	}

// 	std::for_each(connections_.begin(), connections_.end(),
// 		boost::bind(&Connection::update, timeElapse));
}

ConnectionPtr ConnectionManager::findConnectionFromID(uint64 id)
{
	ConnectionMapType::iterator it = connections_.find( id );
	if (it != connections_.end())
	{
		return (it->second);
	}

	return ConnectionPtr();
}